package org.gthelper.imageProcess;

//import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;

import javax.media.jai.RasterFactory;
import javax.media.jai.remote.SerializableRenderedImage;

import org.gthelper.hdpWritable.HdpRenderedImageWritable;

public class MeanFilterTreater {
	
	public static HdpRenderedImageWritable image_MeanFilter(HdpRenderedImageWritable sourceimage,int residule )
	{
		if(sourceimage==null) return null;
		RenderedImage sourceRenderedImage = sourceimage.sri;
		ColorModel colorModel = sourceRenderedImage.getColorModel();
//		WritableRaster sourceraster = (WritableRaster)(sourceRenderedImage).getData();
		Raster rst = sourceRenderedImage.getData();
//		Point pt = new Point(rst.getSampleModelTranslateX(),rst.getSampleModelTranslateY());
		WritableRaster sourceraster = Raster.createWritableRaster(rst.getSampleModel(),rst.getDataBuffer(),null);
		int width_new = sourceRenderedImage.getWidth()-2*residule;
		int height_new = sourceRenderedImage.getHeight()-2*residule;
		int bandnum = sourceRenderedImage.getSampleModel().getNumBands();
		int databuffertype = sourceRenderedImage.getData().getDataBuffer().getDataType();
		WritableRaster resultRaster = RasterFactory.createBandedRaster(databuffertype,width_new,height_new,bandnum,null);
		int rec_num = residule*2+1;
		int rec_num_2 = rec_num*rec_num;
		for(int k=0;k<bandnum;k++)
		{
			for(int i=0;i<width_new;i++)
			{
				for(int j=0;j<height_new;j++)
				{
					double sum=0;
					for(int split_i=0;split_i<rec_num;split_i++)
					{
						for(int split_j=0;split_j<rec_num;split_j++)
						{
							sum+=sourceraster.getSampleDouble(i+split_i, j+split_j, k);
						}
					}
					double value_new = sum/rec_num_2;
					resultRaster.setSample(i, j, k, value_new);
				}
			}
		}
		BufferedImage resultBufferedImage = new BufferedImage(colorModel, resultRaster, false, null);
		HdpRenderedImageWritable splitHdpRenderedImageWritable = new HdpRenderedImageWritable();
		splitHdpRenderedImageWritable.set(sourceimage.name,sourceimage.number_x,sourceimage.number_y,
			  sourceimage.position_x+residule,sourceimage.position_y+residule,
			  new SerializableRenderedImage(resultBufferedImage,true));
		return splitHdpRenderedImageWritable;
	}

}
